package weixin.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * http请求
 */
public class HttpUtils {
    /**
     * @param url      链接地址
     * @param method   方法
     * @param paramMap 参数
     * @return
     */
    public static String sendRequest(String url, HttpMethod method, MultiValueMap<String, Object> paramMap) {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        return new RestTemplate().exchange(url, method, httpEntity, String.class).getBody();
    }


    public static String sendPostRequest(String url, HttpHeaders headers, MultiValueMap<String, Object> paramMap) {
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        return new RestTemplate().exchange(url, HttpMethod.POST, httpEntity, String.class).getBody();
    }

    public static String sendGetRequest(String url, HttpHeaders headers, Map<String, Object> paramMap) {
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(null, headers);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap).getBody();    }

    /**
     *
     * @param url
     * @param object
     * @return
     */
    public static String sendPostRequestJson(String url, Object object) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(object), headers);
        return  new RestTemplate().postForEntity(url, entity, String.class).getBody();
    }
}
